use actix_web::{web, Error, HttpResponse};
use actix_multipart::Multipart;
use futures::{StreamExt, TryStreamExt};
use std::io::Write;
use tesseract::Tesseract;

pub async fn extract_text(mut payload: Multipart) -> Result<HttpResponse, Error> {
    // 读取上传的图片
    if let Ok(Some(mut field)) = payload.try_next().await {
        let mut bytes = Vec::new();
        while let Some(chunk) = field.next().await {
            bytes.extend_from_slice(&chunk?);
        }

        // 保存临时文件
        let temp_path = format!("/tmp/{}.png", uuid::Uuid::new_v4());
        std::fs::write(&temp_path, &bytes)?;

        // 初始化 Tesseract
        let tess = Tesseract::new(None, Some("chi_sim+eng")).unwrap();
        let text = tess.set_image(&temp_path)
            .expect("设置图片失败")
            .recognize()
            .expect("识别失败")
            .get_text()
            .expect("获取文本失败");

        // 删除临时文件
        std::fs::remove_file(temp_path)?;

        Ok(HttpResponse::Ok().json(serde_json::json!({
            "text": text,
            "status": "success"
        })))
    } else {
        Ok(HttpResponse::BadRequest().json(serde_json::json!({
            "status": "error",
            "message": "未找到上传的图片"
        })))
    }
}